<template>
    <view>
        <cu-custom bgColor="bg-gradual-green">
            <view slot="left" @click="onArea" style="padding-left:16rpx;">
                <text class="cuIcon-locationfill text-white"></text> {{ location ? location.area : '选择城市' }}
            </view>
            <block slot="content">宠物救助站</block>
        </cu-custom>
        <!-- banner -->
        <swiper class="card-swiper round-dot bg-white " :indicator-dots="true" :circular="true" :autoplay="true"
            interval="5000" duration="500" @change="cardSwiper" indicator-color="#8799a3" indicator-active-color="#0081ff">
            <swiper-item v-for="(item,index) in swiperList" :key="index" :class="cardCur==index?'cur':''" @click="onWebView">
                <view class="swiper-item">
                    <image :src="baseUrl+item.image" mode="aspectFill"></image>
                    <!-- <video :src="item.url" autoplay loop muted :show-play-btn="false" :controls="false" objectFit="cover" v-if="item.type=='video'"></video> -->
                </view>
            </swiper-item>
        </swiper>
        <!-- nav -->
        <view class="bg-white padding homeTabs">
            <view class="grid col-4">
                <view class="bg-img" v-for="(item,index) in avatar" :key="index" @click="toNav('nav?id='+index)">
                    <image :src="item.icon" mode="scaleToFill" class="pic"></image>
                    <view class="text">{{ item.name }}</view>
                </view>
            </view>
        </view>
        <!-- 广告 -->
        <ad unit-id="adunit-82e295cfca0abe3e" ad-type="grid" grid-opacity="0.8" grid-count="5" ad-theme="white"></ad>
        <!-- tab -->
        <scroll-view scroll-x class="bg-white nav text-center margin-top" :style="{top:CustomBar+'px'}">
            <view class="cu-item" :class="index==TabCur?'text-green cur':''" v-for="(item,index) in navList" :key="index"
                @tap="tabSelect" :data-id="index">
                {{ item.name }}
            </view>
        </scroll-view>

        <!-- 卡片 -->
        <view class="cu-card case" v-for="(item,index) in navList[TabCur].list" :key="index" @click="toNav('/pages/goods/adopt?post_id=' + item.post_id)">
            <view class="cu-item shadow">
                <view class="image">
                    <view class="end" v-if="item.pickup_user_id && item.pickup_id">已领养</view>
                    <image :src="item.imageArray[0]" mode="aspectFill"></image>
                    <view class="cu-tag bg-gradual-green" v-if="item.type == 1">领养</view>
                    <view class="cu-tag bg-gradual-orange" v-if="item.type == 2">救助</view>
                    <view class="cu-tag bg-gradual-red" v-if="item.type == 3">丢失</view>
                    <view class="cu-tag bg-gradual-blue" v-if="item.type == 4">帮助</view>
                    <view class="cu-bar bg-shadeBottom">
                        <text class="text-cut">{{ item.content }}</text>
                        <!-- <text class="text-cut">{{ item.city }}</text> -->
                    </view>
                </view>
                <view class="cu-list menu-avatar">
                    <view class="cu-item">
                        <view class="cu-avatar round lg" v-if="item.poster.avatar" :style="{'background-image':'url(' + item.poster.avatar + ')'}"></view>
                        <view class="cu-avatar round lg" v-else></view>
                        <view class="content flex-sub">
                            <view class="text-grey">{{ item.poster.nickname }}</view>
                            <view class="text-gray text-sm flex justify-between">
                                {{ item.createtime_text | formatDate }}
                                <view class="text-gray text-sm">
                                    <text class="cuIcon-attentionfill margin-lr-xs"></text> {{ item.view }}
                                    <text class="cuIcon-appreciatefill margin-lr-xs"></text> {{ item.like.number }}
                                    <text class="cuIcon-messagefill margin-lr-xs"></text> {{ item.replies }}
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
                <view class="padding flex justify-between">
                    <view>
                        <text class='cuIcon-locationfill text-orange'></text>
                        <text class='text-orange'>{{ item.address }}</text>
                    </view>
                    <view class="text-blue text-sm text-right" v-if="location">距离您当前{{ item.distance.toFixed(2) }}km</view>
                </view>
            </view>
        </view>

        <!-- 加载 -->
        <view class="cu-load load-modal" v-if="loadModal">
            <!-- <view class="cuIcon-emojifill text-orange"></view> -->
            <image src="/static/logo.png" mode="aspectFit"></image>
            <view class="gray-text">加载中...</view>
        </view>
        
        <roof></roof>
        
        <view class="cu-tabbar-height"></view>
        <tabs :page="1"></tabs>
    </view>
</template>

<script>
    import Tabs from '../tabs/index.vue';
    import Roof from '../roof/index.vue';
    import {
        mapState,
        mapActions
    } from 'vuex';
    export default {
        name: 'index',
        components: {
            Tabs,
            Roof
        },
        data() {
            return {
                baseUrl: this.$store.state.baseUrl,
                StatusBar: this.StatusBar,
                CustomBar: this.CustomBar,
                avatar: [{
                    icon: '../../static/nav3.png',
                    name: '领养'
                }, {
                    icon: '../../static/nav1.png',
                    name: '救助'
                }, {
                    icon: '../../static/nav2.png',
                    name: '丢失'
                }, {
                    icon: '../../static/nav4.png',
                    name: '帮助'
                }],
                swiperList: [],
                cardCur: 0,
                dotStyle: false,
                TabCur: 0,
                scrollLeft: 0,
                navList: [{
                    name: '最新发布',
                    page: 1,
                    list: [],
                    last_page: 1,
                    refresh: true
                }, {
                    name: '最热帖子',
                    page: 1,
                    list: [],
                    last_page: 1,
                    refresh: true

                }, {
                    name: '离我最近',
                    page: 1,
                    list: [],
                    last_page: 1,
                    refresh: true
                }],
                loadModal: false, //加载
            }
        },
        filters: {
            formatDate(time) {
                return time.substring(0, 10)
            }
        },
		computed: {
			...mapState(['location'])
		},
        onShareAppMessage(res) {
        	if (res.from === 'button') { // 来自页面内分享按钮
        		console.log(res.target)
        	}
        	return {
        		title: '宠助助',
        		path: '/pages/index/index.vue',
        		imageUrl: 'https://wzlive.club//uploads/20200327/32532c95badeed675fa8ef2f58fcd57a.png',
        	}
        },
        onShow() {},
        onLoad() {
			
            // this.getLocation(); //获取所在城市
            this.getBanner();
            this.getHomeList(true);
            
            uni.$on('update', (data) => {
                this.getHomeList(true);
            })
        },
        onReachBottom() {
            this.getHomeList();
        },
        methods: {
            ...mapActions(['setLocation']),
            onWebView(){
                console.log(11)
                uni.navigateTo({
                    url:'/pages/ceshi/index'
                })
            },
            cardSwiper(e) {
                this.cardCur = e.detail.current
            },
            tabSelect(e) {
                this.TabCur = e.currentTarget.dataset.id;
                this.scrollLeft = (e.currentTarget.dataset.id - 1) * 60;
                this.getHomeList();
            },
            toNav(link) {
                uni.navigateTo({
                    url: link
                })
            },
            onArea() {
                uni.chooseLocation({
                    success: (res) => {
                        console.log(res,)
                        let reg = /.+?(省|市|自治区|自治州|县|区)/g;
                        
                        let location = {
                            latitude:res.latitude.toString(),
                            longitude:res.longitude.toString(),
                            area:(res.address.match(reg))[1]
                        }
                        
                        uni.setStorageSync('location',JSON.stringify(location));
                        this.setLocation(location)
                      
                    },
                    fail: (err) => {
                        if (err.errMsg == 'chooseLocation:fail auth deny' || err.errMsg == 'chooseLocation:fail authorize no response') {
                            uni.showModal({
                                title: '请求授权当前位置',
                                content: '需要获取您的地理位置，请确认授权',
                                success: (res) => {
                                    if (res.confirm) {
                                        uni.openSetting(); // 打开地图权限设置
                                    } else if (res.cancel) {
                                        uni.showToast({
                                            title: '你拒绝了授权，无法获得周边信息',
                                            icon: 'none',
                                            duration: 1000
                                        })
                                    }
                                }
                            });
                        }
                    },
                    complete: () => {
                        this.getHomeList(true);
                    }
                });
            },
         //    getLocation() {
         //        //获取现在所在的城市
         //        uni.getLocation({
         //            type: 'wgs84',
         //            success: (res) => {
         //               this.location.latitude = res.latitude.toString();
         //               this.location.longitude = res.longitude.toString();
         //               uni.request({
         //                    header: {
         //                        "Content-Type": "application/text"
         //                    },
         //                    url: 'http://apis.map.qq.com/ws/geocoder/v1/?location=' + this.location.latitude +
         //                        ',' + this.location.longitude +
         //                        '&key=MVGBZ-R2U3U-W5CVY-2PQID-AT4VZ-PDF35',
         //                    success: (re) => {
         //                        console.log(re)
         //                        if (re.statusCode === 200) {
         //                            let reg = /.+?(省|市|自治区|自治州|县|区)/g;
         //                            this.location.area = (re.data.result.address.match(reg))[1];
									
									// console.log(this.area)
         //                            console.log("获取中文街道地理位置成功")
         //                        } else {
         //                            console.log("获取信息失败，请重试！")
         //                        }
         //                    }
         //                });
         //            },
         //            complete: () => {
         //                this.getHomeList(true);
         //            }
         //        });
         //    },
            //接口请求
            getBanner() { //获取广告图
                this.$http.post('getBanner').then(res => {
                    this.swiperList = res.data;
                    console.log(res, this.$store.state.baseUrl)

                })
            },
            getHomeList(reset = false) { //获取列表
                if (reset) {
                    this.navList.forEach(e => {
                        e.refresh = true;
                        e.page = 1;
                        e.last_page = 1;
                    })
                }
                let navIndex = this.navList[this.TabCur];

                console.log(navIndex.last_page, navIndex.page, navIndex.refresh)

                if (this.loadModal) { //防止多次刷新
                    return;
                }
                
                if (navIndex.last_page < navIndex.page && !navIndex.refresh) {
                    //最后一页和当前页面相同就不返回
                    //refresh为false说明已经不是第一次点进去了,满足2个条件只有一种可能,就是没有下一页了
                    uni.showToast({
                        title: '没有更多内容',
                        icon: 'none'
                    })

                    return;
                }
                this.loadModal = true;

                this.$http.post('getHomeList', {
                    sort: this.TabCur + 1,
                    limit: 10,
                    page: navIndex.page,
                    lat: this.location ? this.location.latitude : '',
                    lng: this.location ? this.location.longitude : ''
                }).then(res => {
                    navIndex.last_page = res.data.last_page;

                    if (navIndex.page <= navIndex.last_page  ) {
                        navIndex.page++;
                    }

                    if (navIndex.refresh) { //为true表示第一次加载 
                        navIndex.list = res.data.data; //把数据直接放进去 还是清空,前面的数据 刷新用
                        navIndex.refresh = false;
                    } else {

                        //不是第一次加载,push进去
                        res.data.data.forEach(e => {
                            navIndex.list.push(e);
                        })
                    }

                    this.loadModal = false;

                    console.log(navIndex, res.data.data)
                })
            }
        }
    }
</script>

<style scoped lang="less">
    .homeTabs {
        .pic {
            display: block;

            margin: 0 auto;

            width: 140rpx;
            height: 140rpx;
            border-radius: 50%;

            overflow: hidden;
        }

        .text {
            text-align: center;
            font-size: 32rpx;
            color: #333;

            margin-top: 16rpx;
        }
    }


    .nav {
        position: sticky;
        z-index: 9999;
    }
</style>
